#!/usr/bin/env python3
"""
数据库初始化脚本
"""
import os
import sys
from pathlib import Path
from sqlalchemy.orm import Session

# 添加项目根目录到Python路径
sys.path.append(str(Path(__file__).parent.parent))

from app.core.database import SessionLocal, engine, Base
from app.models import user, department, employee, project, task
from app.services.auth_service import AuthService
from app.schemas.user import UserCreate
from app.schemas.department import DepartmentCreate
from app.schemas.employee import EmployeeCreate
from app.schemas.project import ProjectCreate
from app.schemas.task import TaskCreate

def create_initial_data(db: Session):
    """创建初始数据"""
    print("🚀 开始创建初始数据...")
    
    # 创建初始部门
    dept_data = DepartmentCreate(
        name="技术部",
        description="负责技术开发和维护"
    )
    
    # 检查部门是否已存在
    existing_dept = db.query(department.Department).filter(
        department.Department.name == dept_data.name
    ).first()
    
    if not existing_dept:
        new_dept = department.Department(**dept_data.dict())
        db.add(new_dept)
        db.commit()
        db.refresh(new_dept)
        print(f"✅ 创建部门: {new_dept.name}")
    else:
        new_dept = existing_dept
        print(f"⚠️ 部门已存在: {new_dept.name}")
    
    # 创建管理员用户
    auth_service = AuthService(db)
    
    admin_user = auth_service.get_user_by_username("admin")
    if not admin_user:
        admin_data = UserCreate(
            username="admin",
            email="admin@example.com",
            password="admin123",
            full_name="管理员",
            department_id=new_dept.id
        )
        admin_user = auth_service.create_user(admin_data)
        print(f"✅ 创建管理员用户: {admin_user.username}")
    else:
        print(f"⚠️ 管理员用户已存在: {admin_user.username}")
    
    # 创建测试员工
    test_employee = db.query(employee.Employee).filter(
        employee.Employee.employee_code == "EMP001"
    ).first()
    
    if not test_employee:
        emp_data = EmployeeCreate(
            employee_code="EMP001",
            full_name="张三",
            email="zhangsan@example.com",
            phone="13800138000",
            position="软件工程师",
            department_id=new_dept.id,
            hire_date="2024-01-01",
            salary=15000.00
        )
        test_employee = employee.Employee(**emp_data.dict())
        db.add(test_employee)
        db.commit()
        db.refresh(test_employee)
        print(f"✅ 创建测试员工: {test_employee.full_name}")
    else:
        print(f"⚠️ 测试员工已存在: {test_employee.full_name}")
    
    # 创建测试项目
    test_project = db.query(project.Project).filter(
        project.Project.name == "企业管理系统"
    ).first()
    
    if not test_project:
        # 直接创建Project对象，因为ProjectCreate可能需要额外的参数
        test_project = project.Project(
            name="企业管理系统",
            description="开发和部署企业管理系统",
            status=project.ProjectStatus.IN_PROGRESS,
            start_date="2024-01-01",
            end_date="2024-12-31",
            budget=1000000.00,
            created_by=admin_user.id  # 使用created_by而不是manager_id
        )
        db.add(test_project)
        db.commit()
        db.refresh(test_project)
        print(f"✅ 创建测试项目: {test_project.name}")
    else:
        print(f"⚠️ 测试项目已存在: {test_project.name}")
    
    # 创建测试任务
    test_task = db.query(task.Task).filter(
        task.Task.title == "系统架构设计"
    ).first()
    
    if not test_task:
        # 直接创建Task对象
        test_task = task.Task(
            title="系统架构设计",
            description="设计系统的整体架构",
            status=task.TaskStatus.IN_PROGRESS,
            priority=task.TaskPriority.HIGH,
            due_date="2024-02-01",
            project_id=test_project.id,
            assigned_to=admin_user.id
        )
        db.add(test_task)
        db.commit()
        db.refresh(test_task)
        print(f"✅ 创建测试任务: {test_task.title}")
    else:
        print(f"⚠️ 测试任务已存在: {test_task.title}")
    
    print("🎉 初始数据创建完成！")

def main():
    """主函数"""
    print("🔧 开始初始化数据库...")
    
    # 创建所有表
    print("📊 创建数据库表...")
    Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建完成")
    
    # 创建初始数据
    db = SessionLocal()
    try:
        create_initial_data(db)
    except Exception as e:
        print(f"❌ 创建初始数据时出错: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    main()